package com.tmall.testgen.common.util;

import java.io.File;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.tmall.testgen.client.genfile.TotalGenHandler;


/**
 * @author haojia
 * @date 2014-07-04
 */
public class StringUtil {

	/**
	 * 字符替换.到/
	 * @return
	 */
	public static String replaceD2G(String s){
		return s.replaceAll("\\.", "\\/");
	}
	public static String replaceG2D(String s){
		return s.replaceAll("/", ".");
	}
	
	
	public static String cleanStr(String str) {
		String dest = "";
		if (str!=null) {
			Pattern p = Pattern.compile("\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}

	
	
	

	
	/**
	 * 对拦截表达式格式化处理
	 * 1、trim
	 * 2、(之前之后不可有空格
	 * 3、)之前不可有空格
	 * 4、,之前之后不可有空格
	 * 5、两个以上空格都变成1个
	 */
	public static String formatMethod(String str){
		str=str.trim();
		while(str.indexOf("  ")>0){
			str=str.replaceAll("  ", " ");
		}
		while(str.indexOf(" (")>0){
			str=str.replaceAll(" \\(", "(");
		}
		while(str.indexOf("( ")>0){
			str=str.replaceAll("\\( ", "(");
		}
		while(str.indexOf(" )")>0){
			str=str.replaceAll(" \\)", ")");
		}
		while(str.indexOf(") ")>0){
			str=str.replaceAll("\\) ", ")");
		}
		while(str.indexOf(" ,")>0){
			str=str.replaceAll(" ,", ",");
		}
		while(str.indexOf(", ")>0){
			str=str.replaceAll(", ", ",");
		}
		
		return str;
	}
	// 
    public static void main(String[] args) {
        //mockdes:com\.test\.MyTest$mock.*\(\s*\)\:.*,nfo.getClassName()com.test.MyTest,moctTest(int a):String
        isMatchMethod("com\\.test\\.MyTest$mock.*\\(\\s*\\)\\:.*","mockTest(int a):String");
        //      String exp="com\\.test\\.Test[^\\.]*.method\\(\\s*(int|Integer)\\s+.*\\)";
//      String m="com.test.Testaa.method( int u,int b )";

//      String exp="com\\.test\\.Test[^\\.]*.method\\((\\w*\\s+\\w+,){2}\\s*(int|Integer)\\s+.*\\)";
//      String m="com.test.Testaa.method(int a,float f,int b)”;

        //String exp="com\\.test\\.\\w*\\.?Test[^\\.]*.method\\((\\w*\\s+\\w+,){2}\\s*(int|Integer)\\s+.*\\)";
        String exp="asdf$s";
        String m="com.test.ppp.Testaa.method(int a,float f,int b)";
        
        //\.test\.MyTest$mock.*\(\s*\)\:.*,nfo.getClassName()
        System.out.println(isMatchMethod(exp,m));
        
    }
	public static boolean isMatchClass(String regEx,String source){
	    
		if(regEx==null||regEx.trim().length()==0)
		    return false;
		if(regEx.indexOf("$")>0){
		    regEx=regEx.substring(0, regEx.indexOf("$"));
		}
		Pattern sp=Pattern.compile(regEx);
		return sp.matcher(source).matches();
	}
	
	public static boolean isMatchMethod(String regEx,String source){
	    if(regEx==null||regEx.trim().length()==0)
            return false;
        if(regEx.indexOf("$")<=0){
            return true;
        }
        regEx=regEx.substring(regEx.indexOf("$")+1);
        
        Pattern sp=Pattern.compile(regEx);
        return sp.matcher(source).matches();
	}
	
	public static String getUid(){
		UUID uuid = UUID.randomUUID();    
		return uuid.toString().replaceAll("-", "");
	}
	
	public static String getTargetProjectName(String targetProjectPath){
		return targetProjectPath.substring(targetProjectPath.lastIndexOf(TotalGenHandler.split)+1);
	}

	public static String getTargetProjectRootPath(String targetProjectPath){
		int lastPos=targetProjectPath.lastIndexOf(TotalGenHandler.split);
		int lastPos2=targetProjectPath.lastIndexOf("\\");
		int pos=Math.max(lastPos, lastPos2);
		return targetProjectPath.substring(0,pos);
	}
	
	public static String getTreeNodeName(Object obj){
		String name="";
		if(obj==null)
			return "null";
//		if(obj instanceof FieldClassAndValue)
//			obj=((FieldClassAndValue)obj).getValue();
		
		if(Object2TreeMap.isBasicType(obj)){
			return obj+"";
		}else{
			return "["+obj.getClass().getName()+"]";
		}
	}
	
	public static int getLastIndexOfSplit(String str){
		int lastPos=str.lastIndexOf(TotalGenHandler.split);
		int lastPos2=str.lastIndexOf(File.separator);
		return Math.max(lastPos, lastPos2);
	}
	
	  public static final String normalizePath(String path)
	    {
	      if(path==null)
	          return null;
	      
	        // Normalize the slashes and add leading slash if necessary
	        String normalized = path;
	        if (normalized.indexOf('\\') >= 0)
	        {
	            normalized = normalized.replace('\\', '/');
	        }

	        if (!normalized.startsWith("/"))
	        {
	            normalized = "/" + normalized;
	        }

	        // Resolve occurrences of "//" in the normalized path
	        while (true)
	        {
	            int index = normalized.indexOf("//");
	            if (index < 0)
	                break;
	            normalized = normalized.substring(0, index) +
	            normalized.substring(index + 1);
	        }

	        // Resolve occurrences of "%20" in the normalized path
	        while (true)
	        {
	            int index = normalized.indexOf("%20");
	            if (index < 0)
	                break;
	            normalized = normalized.substring(0, index) + " " +
	            normalized.substring(index + 3);
	        }

	        // Resolve occurrences of "/./" in the normalized path
	        while (true)
	        {
	            int index = normalized.indexOf("/./");
	            if (index < 0)
	                break;
	            normalized = normalized.substring(0, index) +
	            normalized.substring(index + 2);
	        }

	        // Resolve occurrences of "/../" in the normalized path
	        while (true)
	        {
	            int index = normalized.indexOf("/../");
	            if (index < 0)
	                break;
	            if (index == 0)
	                return (null);  // Trying to go outside our context
	            int index2 = normalized.lastIndexOf('/', index - 1);
	            normalized = normalized.substring(0, index2) +
	            normalized.substring(index + 3);
	        }

	        // Return the normalized path that we have completed
	        return (normalized);
	    }

	  
		/**
		 * 按照类规则进行转换， Object 转为object
		 * @param className
		 * @return
		 */
		public static String firstCharToLower(String className){
			//className=className.substring(className.lastIndexOf(".")+1);
			
			
			 StringBuffer sb = new StringBuffer();
			 boolean continueChange=true;
	        for(int i=0;i<className.length();i++){  
	            char c = className.charAt(i);  
	            if(Character.isUpperCase(c)){ 
	            	if(continueChange){
	            		 sb.append(Character.toLowerCase(c));  
	            	}else{
	            		sb.append(c); 
	            	}
	               
	            }else if(Character.isLowerCase(c)){ 
	            	if(continueChange)
	            		continueChange=false;

	            	if(continueChange){
	            		 sb.append(Character.toLowerCase(c));  
	            	}else{
	            		sb.append(c); 
	            	}  
	            }else{
	                sb.append(c); 
	            }
	        }  
	        
	        
			  return  sb.toString(); 
			    
			//return className.substring(0, 1).toLowerCase()+className.substring(1);
		}
		
		public static String getClassSimpleNameFromClassName(String className){
			return className.substring(className.lastIndexOf(".")+1);
		}
		public static String getPackageFromClassName(String className){
			int pos=className.lastIndexOf(".");
			if(pos<0)
				return null;
			return className.substring(0, pos);
		}
	
}
